package com.moon.game.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具类
 * 
 * @author moon
 * 
 */
public class MD5 {
	
	public static final String MD5Key = "MooN";
	public static String encode(String oid, String pswd, String proxyKey)
			throws NoSuchAlgorithmException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		if (pswd == null)
			pswd = "";
		byte[] d = md5.digest((pswd + proxyKey + oid).getBytes());
		return byte2hex(d, d.length / 2 - 2, d.length / 2 + 2);
	}

	public static String encode(String param) throws NoSuchAlgorithmException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		byte[] d = md5.digest((param).getBytes());
		return byte2hex(d, d.length / 2 - 2, d.length / 2 + 2);
	}

	private static String byte2hex(byte[] b, int start, int end) {
		String hs = "";
		String tmp = "";
		for (int n = start; n < end; n++) {
			tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (tmp.length() == 1) {
				hs = hs + "0" + tmp;
			} else {
				hs = hs + tmp;
			}
		}
		tmp = null;
		return hs;
	}

	public static String encodeAndTime(String str, String pswd, String proxyKey)
			throws NoSuchAlgorithmException {
		return encode(str, pswd, proxyKey) + "-" + (int) (System.currentTimeMillis() / 1000);
	}

}
